<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./数据.js"></script>
    <style>
        select{
            width: 200px;
            height: 30px;
            margin: 10px;
        }
        option{
            text-align: center;
        }
    </style>
</head>
<body>
    <select value="" id="province">
        <option value="">请选择</option>
    </select>
    <select value="" id="city">
        <option value="">请选择</option>
    </select>
    <select value="" id="contry">
        <option value="">请选择</option>
    </select>
</body>
<script>
    // 3.分别获取这三个下拉框
    let province = document.getElementById("province");
    let city = document.getElementById("city");
    let area = document.getElementById("contry");
    let res = document.createDocumentFragment();
    // 4.遍历数据
    for (let i = 0; i < data.length; i++) {
        console.log(data[i]);
        let option = document.createElement("option");
        option.innerHTML = data[i].value;
        option.value = data[i].code;
        // 将option添加到frag中
        res.appendChild(option);
    }
    // 5.添加到省级下拉框中
    province.appendChild(res);

    // 1.定义一个空数组，用于存储市级数据
    let cityArr = []
    // 2.为省级下拉框添加onchange事件,onchange事件会在下拉框的值发生变化时触发,当省级数据发生变化时，获取市级数据,并添加到市级下拉框中
    province.onchange = function () {
        //清空市级与区级中的数据，防止重复,因为省级数据变化时，市级数据也会变化
        city.innerHTML="<option value=\"\">请选择</option>"
        contry.innerHTML="<option value=\"\">请选择</option>"
        // 3.遍历省级数据，获取市级数据
        for (let i = 0; i < data.length; i++) {
            if (data[i].code == this.value) {
                cityArr = data[i].children;
                break;
            }
        }
        // 4.遍历市级数据
        for (let j = 0; j < cityArr.length; j++) {
            let option = document.createElement("option");
            option.innerHTML = cityArr[j].value;
            option.value = cityArr[j].code;
            res.appendChild(option);
        }
        city.appendChild(res);
    }
    let contryArr = []
    city.onchange = function () {
        contry.innerHTML="<option value=\"\">请选择</option>"
        for (let i = 0; i < cityArr.length; i++) {
            if (cityArr[i].code == this.value) {
                contryArr = cityArr[i].children;
                break;
            }
        }
        for (let j = 0; j < contryArr.length; j++) {
            let option = document.createElement("option");
            option.innerHTML = contryArr[j].value;
            option.value = contryArr[j].code;
            res.appendChild(option);
        }
        contry.appendChild(res);
    }
</script>
</html>